package com.wangyadong.hobby.schedule.jobtask.dsa;


/**
 * 两个链表 相加
 * 倒数输入
 * 3->1->5->null 和 5->9->2->null，返回 8->0->8->null
 * 543 +876   3201
 */
public class TwoNumsAdd {
    public void solution(NodeList node1, NodeList node2) {
        int carry = 0;
        NodeList tmp = new NodeList(0, null);
        NodeList cur = tmp;
        while (node1 != null || node2 != null) {
            int node1value = node1 != null ? node1.value : 0;
            int node2value = node2 != null ? node2.value : 0;
            int value = node1value + node2value + carry;
            carry = value / 10;
            if (carry > 0) {
                value = value % 10;
            }
            cur.next = new NodeList(value, null);
            cur = cur.next;
            node1 = node1 == null ? null : node1.next;
            node2 = node2 == null ? null : node2.next;
        }
        if (carry > 0) {
            cur.next = new NodeList(carry, null);
        }
        tmp = tmp.next;
        while (tmp != null) {
            System.out.print(tmp.value);
            tmp = tmp.next;
        }
        System.out.println();
    }

    public static class NodeList {
        public int value;
        public NodeList next;

        public NodeList(int value, NodeList next) {
            this.value = value;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        NodeList node1 = new NodeList(0, null), node2 = new NodeList(0, null);
//        install(3456);
        //7243+564
        install(node1, 34271);
        install(node2, 4654);
        //32109876
        //  876543+
        //      66
        TwoNumsAdd numsAdd = new TwoNumsAdd();
        numsAdd.solution(node1.next, node2.next);
    }


    public static void install(NodeList node1, int num) {
        num = num / 10;
        NodeList nodeList = null;
        while (num != 0) {
            nodeList = new NodeList(num % 10, null);
            node1.next = nodeList;
            node1 = node1.next;
            num = num / 10;
        }

    }

    public static void install(int num) {
        NodeList node1 = new NodeList(0, null);
        num = num / 10;
        NodeList nodeList = node1;
        while (num != 0) {
            NodeList nodeList1 = new NodeList(num % 10, null);
            nodeList.next = nodeList1;
            nodeList = nodeList.next;
            num = num / 10;
        }
        System.out.println(node1);
    }

}



